'use strict'

let default_config = `'use strict'

module.exports = {
  port: 8001,
}
`

let default_site = `{
  "path": "../web",
  "home": ["index.html", "index.htm", "home.html"],
  "deny": []
}`

process.chdir(__dirname)

const Titbit = require('titbit')
const fs = require('fs')
const {Resource} = require('titbit-toolkit')

const app = new Titbit({
  debug: true,
  useLimit: true,
  maxConn: 2000,
  maxIPRequest: 160,
  unitTime: 2000,
  globalLog: true,
  logMaxLines: 10000,
  logType: 'file',
  logFile: './tmp/access.log',
  errorLogFile: './tmp/error.log',
  loadInfoFile: '--mem',
  pidFile: './tmp/server.pid'
})

const fsp = fs.promises
let site_file = './website.json'

if (app.isMaster) {
  try {
    fs.accessSync('./tmp')
  } catch (err) {
    fs.mkdirSync('./tmp')
  }

  try {
    fs.accessSync(site_file)
  } catch (err) {
    fs.writeFileSync(site_file, default_site)
  }

  try {
    fs.accessSync('./config.js')
  } catch (err) {
    fs.writeFileSync('./config.js', default_config)
  }
}

const config = require('./config.js')

function fmtSite(si) {
  if (!si.home || (typeof si.home !== 'string' && !Array.isArray(si.home))) {
    si.home = [
      'home.html', 'index.html', 'index.htm'
    ]
  }

  if (!Array.isArray(si.home)) {
    si.home = [si.home]
  }

  if (!si.deny || !Array.isArray(si.deny)) {
    si.deny = null
  }

  if (!si.path) {
    si.path = '../web'
  }
}

let site = require('./website.json')
fmtSite(site)

if (app.isWorker) {
    fs.watchFile(site_file, (cur, prev) => {
      try {
        fs.accessSync(site_file)
      } catch (err) {
        console.log(err)
        fs.writeFileSync(site_file, JSON.stringify(site), {encoding: 'utf8'})
      }

      try {
        let data = fs.readFileSync(site_file, {encoding: 'utf8'})
        let obj = JSON.parse(data)
        for (let k in obj) {
          site[k] = obj[k]
        }

        fmtSite(site)

        console.log('reload site config', site)
      } catch (err) {
        console.error(err)
      }
    })
}

if (app.isWorker) {
  app.get('/', async c => {
    let home_file = ''
    let home_find = false

    for (let hf of site.home) {
      await fsp.access(site.path + '/' + hf)
          .then(res => {
            home_find = true
            home_file = hf
          })
          .catch(err => {
            
          })

      if (home_find) break
    }

    if (!home_file) {
      return c.status(404).send(await fsp.readFile('./pages/404.html', {encoding: 'utf8'}))
    }

    await c.pipe(site.path + '/' + home_file)
  })

  app.pre(async (c, next) => {
    if (site.deny) {
      let ind
      for (let a of site.deny) {
        ind = c.path.indexOf(a)
        if (ind === 0 || ind === 1) {
          return c.status(403).send('deny')
        }
      }
    }

    await next()
  }, {group: '_static'})

  let rse = new Resource({
    staticPath: site.path,
    routePath : '/*',
    routeGroup: '_static',
    decodePath: true,
    maxFileSize: 12_000_000,
    cacheControl: 'max-age=30'
  })

  rse.init(app)
}

app.autoWorker(3)

app.daemon(config.port, '0.0.0.0')
